package scoreCard.LivestockJudging3C;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;

import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Util;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

import scoreCard.LivestockJudging3C.R;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ShareActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share);
		postListView = (ListView) this.findViewById(R.id.postListView);
		allPosts = new ArrayList<FacebookPost>();

		mPrefs = getPreferences(MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);
		if (access_token != null) {
			facebook.setAccessToken(access_token);
		}
		if (expires != 0) {
			facebook.setAccessExpires(expires);
		}

		if (!facebook.isSessionValid()) {
			facebook.authorize(this, new String[] { "publish_stream" },
					new DialogListener() {
						public void onComplete(Bundle values) {
							SharedPreferences.Editor editor = mPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
							getPosts();
							setAdapter();
						}

						public void onFacebookError(FacebookError error) {
						}

						public void onError(DialogError e) {
						}

						public void onCancel() {
						}
					});
		}
		
		final EditText posttext = (EditText)findViewById(R.id.facebookPost);
		final Button postButton = (Button)findViewById(R.id.postButton);
		postButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				if(!posttext.getText().toString().equals("")){
					postToPage(posttext.getText().toString());
					posttext.setText("");
					getPosts();
					aa.notifyDataSetChanged();
					posttext.setText("");
				}
			}
		});
		
		final TextView moreText = (TextView)findViewById(R.id.moreButton);
		moreText.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				numPosts += 5;
				getPosts();
				aa.notifyDataSetChanged();
			}
		});
		
		postListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> av, View view, int index,
					long arg3) {
				String id = allPosts.get(index).getID();
				Intent intent = new Intent(ShareActivity.this,CommentActivity.class);
	    		Bundle info  = new Bundle();
	    		info.putString("ID",id);
	    		intent.putExtras(info);
	    		startActivity(intent);
				
			}
		});
	}
	
	@Override
	public void onResume() {
		super.onResume();
		facebook.extendAccessTokenIfNeeded(this, null);
		getPosts();
		setAdapter();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		facebook.authorizeCallback(requestCode, resultCode, data);
	}

	private void setAdapter() {
		aa = new PostAdapter(this, R.layout.postlayout, allPosts);
		postListView.setAdapter(aa);
		aa.notifyDataSetChanged();
	}
	
	private void postToPage(String message) {
		Bundle bundle = new Bundle();
		bundle.putString("message", message);
		bundle.putString(Facebook.TOKEN, facebook.getAccessToken());
		mAsyncRunner.request("3CLivestockJudging/feed", bundle, "POST",
				new PostRequestListener(), "Post");
	}

	private void getPosts() {
		allPosts.clear();
		JSONObject feed;
		
		try {
			feed = Util.parseJson(facebook.request("3CLivestockJudging/feed"));
			JSONArray dataArray = feed.getJSONArray("data");
			for (int i = 0; i < numPosts; i++) {
				String id = dataArray.getJSONObject(i).getString("id");
				JSONObject from = dataArray.getJSONObject(i).getJSONObject(
						"from");
				String name = from.getString("name");
				String message = dataArray.getJSONObject(i)
						.getString("message");
				String timestamp = dataArray.getJSONObject(i).getString(
						"created_time");
				Date parsedTimestamp = parse(timestamp);
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"MMMM d, yyyy 'at' h:mm a");
				timestamp = dateFormat.format(parsedTimestamp);
		        
				allPosts.add(new FacebookPost(id, name, message, timestamp));
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FacebookError e) {
			e.printStackTrace();
		}
	}

	private void logout() {
		mAsyncRunner.logout(this, new RequestListener() {
			public void onComplete(String response, Object state) {
			}

			public void onIOException(IOException e, Object state) {
			}

			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			public void onFacebookError(FacebookError e, Object state) {
			}
		});
		String method = "DELETE";
		Bundle params = new Bundle();
		/*
		 * this will revoke 'publish_stream' permission Note: If you don't
		 * specify a permission then this will de-authorize the application
		 * completely.
		 */
		params.putString("permission", "publish_stream");
		mAsyncRunner.request("/me/permissions", params, method,
				new RequestListener() {

					public void onComplete(String response, Object state) {
					}

					public void onIOException(IOException e, Object state) {
					}

					public void onFileNotFoundException(
							FileNotFoundException e, Object state) {
					}

					public void onMalformedURLException(
							MalformedURLException e, Object state) {
					}

					public void onFacebookError(FacebookError e, Object state) {
					}
				}, null);
	}
	
	private Date parse(String input) {

		// NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks
		// things a bit. Before we go on we have to repair this.
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");

		// this is zero time so we need to add that TZ indicator for
		if (input.endsWith("Z")) {
			input = input.substring(0, input.length() - 1) + "GMT-00:00";
		} else {
			int inset = 6;

			String s0 = input.substring(0, input.length() - inset);
			String s1 = input.substring(input.length() - inset, input.length());

			input = s0 + "GMT" + s1;
		}

		try {
			return df.parse(input);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}

	}

	private Facebook facebook = new Facebook("326103550760452");
	private AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
	private SharedPreferences mPrefs;
	private ListView postListView;
	private ArrayAdapter<FacebookPost> aa;
	private ArrayList<FacebookPost> allPosts;
	private int numPosts = 10;

	private class PostRequestListener implements RequestListener {

		public void onComplete(final String response, final Object state) {
			getPosts();
			runOnUiThread(new Runnable() {
				public void run() {
					getPosts();
					setAdapter();
				}
			});
		}

		public void onIOException(IOException e, Object state) {

		}

		public void onFileNotFoundException(FileNotFoundException e,
				Object state) {

		}

		public void onMalformedURLException(MalformedURLException e,
				Object state) {

		}

		public void onFacebookError(FacebookError e, Object state) {

		}
	}
}
